﻿using System;
using System.Text;
using System.Threading.Tasks;
using GMS.Models.Jwt;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace GMS.API.Config
{
    public static class JwtConfig
    {

        public static void InitJwt(this IServiceCollection services, IConfiguration configuration)
        {
            //注入JwtSetting配置
            services.Configure<JwtSetting>(configuration.GetSection("JwtSettings"));

            //获取JwtSetting配置
            var jwtSetting = configuration.GetSection("JwtSettings").Get<JwtSetting>();

            //配置Jwt
            services.AddAuthentication(configureOptions =>
            {
                configureOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                configureOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true, //是否验证SecurityKey
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecretKey)),
                    ValidIssuer = jwtSetting.Issuer,
                    ValidateIssuer = true, //是否验证Issuer
                    ValidAudience = jwtSetting.Audience,
                    ValidateAudience = true, //是否验证Audience
                    ClockSkew = TimeSpan.FromMinutes(jwtSetting.ExpiredDate),
                    ValidateLifetime = true, //是否验证失效时间
                };
            });
        }
    }
}